<?php

namespace App\Service\CallingCards\Article;

use App\Enums\CallingCards\BaseEnum;
use App\Models\FeishuCallingCard\FeishuCallingCardsArticle;
use App\Support\CustomForm\AttributeSupport;
use App\Support\CustomForm\ValidateSupport;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use Psr\SimpleCache\InvalidArgumentException;

class HomeArticleService
{

    /**
     * @param object $requestParams
     * @throws Exception|InvalidArgumentException
     */
    public static function homeArticleAdd(object $requestParams)
    {
        try {
            $createdAt = time();
            if (property_exists($requestParams, "extra") && !empty($requestParams->extra)) {
                try {
                    $extra = json_decode($requestParams->extra, true);
                    if (!empty($extra["extraCreateTime"])) {
                        $createdAt = $extra["extraCreateTime"];
                    }
                } catch (Exception $exception) {

                }
            }
            FeishuCallingCardsArticle::query()->insert(array_merge((array)$requestParams, [
                "status"    => FeishuCallingCardsArticle::STATUS_ON,
                "createdAt" => $createdAt,
                "updatedAt" => time()
            ]));

            self::removeHomeCache();
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * @return Collection
     */
    public static function formInit(): Collection
    {
        AttributeSupport::getInstance(
            "name",
            AttributeSupport::INPUT_TYPE_STRING,
            "标题名称"
        )->setValidateRules(ValidateSupport::getInstance(true)->setContentLength(0, 120));

        AttributeSupport::getInstance(
            "url",
            AttributeSupport::INPUT_TYPE_STRING,
            "跳转地址"
        )->setValidateRules(ValidateSupport::getInstance(true)->setContentLength(0, 255));

        AttributeSupport::getInstance(
            "content",
            AttributeSupport::INPUT_TYPE_TEXT,
            "内容"
        )->setValidateRules(ValidateSupport::getInstance(true));

        AttributeSupport::getInstance(
            "originalImage",
            AttributeSupport::INPUT_TYPE_IMG,
            "原始大图"
        )->setValidateRules(ValidateSupport::getInstance(true));

        AttributeSupport::getInstance(
            "thumbImage",
            AttributeSupport::INPUT_TYPE_IMG,
            "预览图"
        )->setValidateRules(ValidateSupport::getInstance(true));

        AttributeSupport::getInstance(
            "weight",
            AttributeSupport::INPUT_TYPE_NUMBER,
            "权重"
        )->setValidateRules(ValidateSupport::getInstance(true))->setValue(0);

        //额外字段
        AttributeSupport::getInstance(
            "extraDetailImages",
            AttributeSupport::INPUT_TYPE_IMG_GROUP,
            "详情图片(多张)"
        )->setValidateRules(ValidateSupport::getInstance(true));

        AttributeSupport::getInstance(
            "extraVideo",
            AttributeSupport::INPUT_VIDEO,
            "视频"
        )->setValidateRules(ValidateSupport::getInstance(true));

        AttributeSupport::getInstance(
            "extraCityText",
            AttributeSupport::INPUT_TYPE_STRING,
            "市级名称"
        )->setValidateRules(ValidateSupport::getInstance(true)->setContentLength(0, 120));

        AttributeSupport::getInstance(
            "extraShopTypeName",
            AttributeSupport::INPUT_TYPE_STRING,
            "店型"
        )->setValidateRules(ValidateSupport::getInstance(true)->setContentLength(0, 120));

        AttributeSupport::getInstance(
            "extraArea",
            AttributeSupport::INPUT_TYPE_NUMBER,
            "面积"
        )->setValidateRules(ValidateSupport::getInstance(true)->setContentLength(0, 120));

        AttributeSupport::getInstance(
            "extraStartBusinessTime",
            AttributeSupport::INPUT_DATE_YMD,
            "开业时间"
        )->setValidateRules(ValidateSupport::getInstance(true));

        AttributeSupport::getInstance(
            "extraView",
            AttributeSupport::INPUT_TYPE_NUMBER,
            "阅读量"
        )->setValidateRules(ValidateSupport::getInstance(true));

        AttributeSupport::getInstance(
            "extraDetailContent",
            AttributeSupport::INPUT_TYPE_RICH_TEXT,
            "详情页信息"
        )->setValidateRules(ValidateSupport::getInstance(true));

        AttributeSupport::getInstance(
            "extraCreateTime",
            AttributeSupport::INPUT_DATETIME,
            "创建时间"
        )->setValidateRules(
            ValidateSupport::getInstance(true)
        )->setCustomAttribute(['format', 'YYYY-MM-DD HH:ii:ss']);

        return collect(array_merge(
            self::homeH5Form(),
            self::homePcForm()
        ));
    }

    /**
     * 官网h5表单
     *
     * @return array[]
     */
    public static function homeH5Form(): array
    {
        return [
            [
                //  首屏轮播图：名字 + 图片
                "type" => FeishuCallingCardsArticle::ARTICLE_TYPE_3,
                "form" => [
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                    (clone AttributeSupport::$attributesMap->url)->setValidateRules(
                        ValidateSupport::getInstance(false)->setContentLength(0, 255)
                    )
                ]
            ],
            [
                // 主打产品：名字 + 图片（来源） + 内容
                "type" => FeishuCallingCardsArticle::ARTICLE_TYPE_4,
                "form" => [
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight
                ]
            ],
            [
                //明星门店秀：地址 + 名称 + 店型 + 面积 + 开业时间 + 内容 + 图片
                "type" => FeishuCallingCardsArticle::ARTICLE_TYPE_5,
                "form" => [
                    (clone AttributeSupport::$attributesMap->name)->setInputDesc("市级名称"),
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                    AttributeSupport::$attributesMap->extraDetailImages
//                    AttributeSupport::$attributesMap->extraCityText,
//                    AttributeSupport::$attributesMap->extraShopTypeName,
//                    AttributeSupport::$attributesMap->extraArea,
//                    AttributeSupport::$attributesMap->extraStartBusinessTime,
                ]
            ],
            [
                //夸父荣誉：名字 + 图片
                "type" => FeishuCallingCardsArticle::ARTICLE_TYPE_6,
                "form" => [
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                ]
            ],
            [
                //加盟案例 - 名称 + 店型 + 面积 + 开业时间 + 内容 + 图片 + 详情（多图）
                "type" => FeishuCallingCardsArticle::ARTICLE_TYPE_7,
                "form" => [
//                    AttributeSupport::$attributesMap->name,
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                    AttributeSupport::$attributesMap->extraDetailImages
//                    AttributeSupport::$attributesMap->extraShopTypeName,
//                    AttributeSupport::$attributesMap->extraArea,
//                    AttributeSupport::$attributesMap->extraStartBusinessTime,
                ]
            ],
            [
                //采访视频：标题 + 简介（视频文件过大，应该放剪辑后的 30s 视频）
                "type" => FeishuCallingCardsArticle::ARTICLE_TYPE_8,
                "form" => [
                    AttributeSupport::$attributesMap->name,
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->content,
                    AttributeSupport::$attributesMap->extraVideo,
                    AttributeSupport::$attributesMap->weight
                ]
            ],
            [
                //新闻 - 标题 + 图片 + 阅读量
                "type" => FeishuCallingCardsArticle::ARTICLE_TYPE_9,
                "form" => [
                    (clone AttributeSupport::$attributesMap->name)
                        ->setInputDesc("新闻标题")
                        ->setValidateRules(ValidateSupport::getInstance(true)->setContentLength(0, 150)),
                    (clone AttributeSupport::$attributesMap->originalImage)->setInputDesc("banner图"),
                    (clone AttributeSupport::$attributesMap->thumbImage)->setInputDesc("列表图"),
                    AttributeSupport::$attributesMap->content,
                    AttributeSupport::$attributesMap->url,
                    AttributeSupport::$attributesMap->weight,
                    AttributeSupport::$attributesMap->extraCreateTime
//                    AttributeSupport::$attributesMap->extraView
                ]
            ],
            [
                //品牌产品
                "type" => FeishuCallingCardsArticle::ARTICLE_TYPE_10,
                "form" => [
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                    AttributeSupport::$attributesMap->extraDetailImages
                ]
            ],
        ];
    }

    /**
     * 官网pc表单
     *
     * @return array[]
     */
    public static function homePcForm(): array
    {
        return [
            [
                //  首屏轮播图：名字 + 图片
                "type" => FeishuCallingCardsArticle::ARTICLE_PC_TYPE_31,
                "form" => [
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                    (clone AttributeSupport::$attributesMap->url)->setValidateRules(
                        ValidateSupport::getInstance(false)->setContentLength(0, 255)
                    )
                ]
            ],
            [
                "type" => FeishuCallingCardsArticle::ARTICLE_PC_TYPE_32,
                "form" => [
                    (clone AttributeSupport::$attributesMap->name)->setInputDesc("产品名称"),
                    (clone AttributeSupport::$attributesMap->content)->setInputDesc("产品描述"),
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                ]
            ],
            [
                //明星门店秀
                "type" => FeishuCallingCardsArticle::ARTICLE_PC_TYPE_33,
                "form" => [
                    (clone AttributeSupport::$attributesMap->name)->setInputDesc("市级名称"),
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                    AttributeSupport::$attributesMap->extraDetailContent
                ]
            ],
            [
                //夸父荣誉
                "type" => FeishuCallingCardsArticle::ARTICLE_PC_TYPE_34,
                "form" => [
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                    (clone AttributeSupport::$attributesMap->content)->setInputDesc("描述"),
                ]
            ],
            [
                //pc-采访视频
                "type" => FeishuCallingCardsArticle::ARTICLE_PC_TYPE_35,
                "form" => [
                    AttributeSupport::$attributesMap->name,
                    (clone AttributeSupport::$attributesMap->originalImage)->setInputDesc("列表图"),
                    AttributeSupport::$attributesMap->content,
                    AttributeSupport::$attributesMap->extraVideo,
                    AttributeSupport::$attributesMap->weight
                ]
            ],
            [
                //pc-新闻资讯
                "type" => FeishuCallingCardsArticle::ARTICLE_PC_TYPE_36,
                "form" => [
                    (clone AttributeSupport::$attributesMap->name)
                        ->setInputDesc("新闻标题")
                        ->setValidateRules(ValidateSupport::getInstance(true)->setContentLength(0, 150)),
                    (clone AttributeSupport::$attributesMap->originalImage)->setInputDesc("banner图"),
                    (clone AttributeSupport::$attributesMap->thumbImage)->setInputDesc("列表图"),
                    AttributeSupport::$attributesMap->content,
                    AttributeSupport::$attributesMap->url,
                    AttributeSupport::$attributesMap->extraCreateTime,
                    AttributeSupport::$attributesMap->weight,
                ]
            ],
            [
                //pc-品牌产品
                "type" => FeishuCallingCardsArticle::ARTICLE_PC_TYPE_37,
                "form" => [
                    (clone AttributeSupport::$attributesMap->name)->setInputDesc("产品名称"),
                    (clone AttributeSupport::$attributesMap->content)->setInputDesc("产品描述"),
                    (AttributeSupport::$attributesMap->originalImage)->setInputDesc("产品详情大图"),
                    AttributeSupport::$attributesMap->weight,
                    (clone AttributeSupport::$attributesMap->thumbImage)->setInputDesc("产品列表图")
                ]
            ],
            [
                //pc-加盟案例
                "type" => FeishuCallingCardsArticle::ARTICLE_PC_TYPE_38,
                "form" => [
                    AttributeSupport::$attributesMap->originalImage,
                    AttributeSupport::$attributesMap->weight,
                    AttributeSupport::$attributesMap->extraDetailContent
                ]
            ],
            [
                //pc-advertisement
                "type" => FeishuCallingCardsArticle::ARTICLE_PC_TYPE_39,
                "form" => [
                    AttributeSupport::$attributesMap->originalImage
                ]
            ],
        ];
    }

    /**
     * @return array|void
     * @throws Exception
     */
    public static function getFormDetail()
    {
        try {
            return self::formInit()->map(function ($typeForm) {
                $typeForm["typeName"] = FeishuCallingCardsArticle::ARTICLE_TYPE_MAP[$typeForm["type"]];
                $typeForm["form"]     = collect($typeForm["form"])
                    ->map(function (AttributeSupport $attribute) {
                        return $attribute->build();
                    })->values();
                return $typeForm;
            })->values()->toArray();

        } catch (Exception $exception) {
            handleException($exception);
        }
    }


    /**
     * @param int $id
     * @return array|void
     * @throws Exception
     */
    public static function homeArticleEditForm(int $id)
    {
        try {

            $article        = FeishuCallingCardsArticle::query()->where("id", $id)->first();
            $articleData    = array_merge($article->toArray(), $article->extra);
            $formAttributes = collect(self::formInit())
                ->where("type", $article->type)
                ->getIterator()
                ->current()["form"];

            return [
                "type"     => $article->type,
                "typeName" => FeishuCallingCardsArticle::ARTICLE_TYPE_MAP[$article->type],
                "form"     => collect($formAttributes)->map(function (AttributeSupport $attribute) use ($articleData) {
                    $attribute->setValue($articleData[$attribute->inputName] ?? "");
                    return $attribute->build();
                })->values()
            ];

        } catch (Exception $exception) {
            handleException($exception);
        }

    }


    /**
     * 官网内容编辑保存
     *
     * @param object $requestParams
     * @throws Exception
     */
    public static function homeArticleEdit(object $requestParams)
    {
        try {
            $article   = FeishuCallingCardsArticle::query()->where("id", $requestParams->id)->first();
            $createdAt = $article->createdAt->timestamp;
            if (property_exists($requestParams, "extra") && !empty($requestParams->extra)) {
                try {
                    $extra = json_decode($requestParams->extra, true);
                    if (!empty($extra["extraCreateTime"])) {
                        $createdAt = $extra["extraCreateTime"];
                    }
                } catch (Exception $exception) {

                }
            }


            FeishuCallingCardsArticle::query()
                                     ->where("id", $requestParams->id)
                                     ->update(array_merge((array)$requestParams, [
                                         "updatedAt" => time(),
                                         "createdAt" => $createdAt
                                     ]));

            self::removeHomeCache();
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 删除官网缓存数据
     *
     * @throws InvalidArgumentException
     */
    public static function removeHomeCache()
    {
        $redisClient = Redis::connection("default")->client();
        $prefix      = vsprintf("%s%s:", [
            Str::slug('home', '_') . '_database_',
            Str::slug('home', '_') . '_cache'
        ]);
        $redisClient->setOption(\Redis::OPT_PREFIX, "");
        $pcKeys = $redisClient->keys("{$prefix}home:pc:page*");
        if (!empty($pcKeys)) {
            $redisClient->del($pcKeys);
        }
        $h5Keys = $redisClient->keys("{$prefix}home:h5:page*");
        if (!empty($h5Keys)) {
            $redisClient->del($h5Keys);
        }
    }

}
